<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SystemSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class SystemSettingController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:view-system-settings')->only(['index', 'show']);
        $this->middleware('permission:create-system-settings')->only(['create', 'store']);
        $this->middleware('permission:edit-system-settings')->only(['edit', 'update', 'batchUpdate']);
        $this->middleware('permission:delete-system-settings')->only(['destroy']);
        $this->middleware('permission:manage-system-settings')->only(['clearCache', 'export', 'import']);
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $group = $request->get('group', 'general');
        
        // 获取所有分组
        $groups = [
            'general' => '基本设置',
            'email' => '邮件配置',
            'security' => '安全设置',
            'interface' => '界面设置',
            'upload' => '文件上传',
            'system' => '系统配置'
        ];
        
        // 获取当前分组的设置
        $settings = SystemSetting::getByGroup($group);
        
        return view('admin.system-settings.index', compact('settings', 'groups', 'group'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $groups = [
            'general' => '基本设置',
            'email' => '邮件配置',
            'security' => '安全设置',
            'interface' => '界面设置',
            'upload' => '文件上传',
            'system' => '系统配置'
        ];
        
        $types = [
            'string' => '字符串',
            'text' => '文本',
            'integer' => '整数',
            'boolean' => '布尔值',
            'json' => 'JSON'
        ];
        
        return view('admin.system-settings.create', compact('groups', 'types'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'key' => 'required|string|unique:system_settings,key|max:255',
            'label' => 'required|string|max:255',
            'value' => 'nullable',
            'type' => 'required|in:string,text,integer,boolean,json',
            'group' => 'required|string|max:255',
            'description' => 'nullable|string',
            'options' => 'nullable|json',
            'is_public' => 'boolean',
            'is_required' => 'boolean',
            'sort_order' => 'integer|min:0'
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        SystemSetting::create($request->all());

        return redirect()->route('admin.system-settings.index', ['group' => $request->group])
            ->with('success', '系统设置创建成功！');
    }

    /**
     * Display the specified resource.
     */
    public function show(SystemSetting $systemSetting)
    {
        $setting = $systemSetting;
        $groups = [
            'general' => '基本设置',
            'email' => '邮件配置',
            'security' => '安全设置',
            'interface' => '界面设置',
            'upload' => '文件上传',
            'system' => '系统配置'
        ];
        
        $types = [
            'string' => '字符串',
            'text' => '文本',
            'integer' => '整数',
            'boolean' => '布尔值',
            'json' => 'JSON'
        ];
        
        return view('admin.system-settings.show', compact('setting', 'groups', 'types'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(SystemSetting $systemSetting)
    {
        $setting = $systemSetting;
        $groups = [
            'general' => '基本设置',
            'email' => '邮件配置',
            'security' => '安全设置',
            'interface' => '界面设置',
            'upload' => '文件上传',
            'system' => '系统配置'
        ];
        
        $types = [
            'string' => '字符串',
            'text' => '文本',
            'integer' => '整数',
            'boolean' => '布尔值',
            'json' => 'JSON'
        ];
        
        return view('admin.system-settings.edit', compact('setting', 'groups', 'types'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, SystemSetting $systemSetting)
    {
        $validator = Validator::make($request->all(), [
            'key' => 'required|string|max:255|unique:system_settings,key,' . $systemSetting->id,
            'label' => 'required|string|max:255',
            'value' => 'nullable',
            'type' => 'required|in:string,text,integer,boolean,json',
            'group' => 'required|string|max:255',
            'description' => 'nullable|string',
            'options' => 'nullable|json',
            'is_public' => 'boolean',
            'is_required' => 'boolean',
            'sort_order' => 'integer|min:0'
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $systemSetting->update($request->all());

        // 重新加载配置到Laravel配置系统
        SystemSetting::reloadConfigs();

        return redirect()->route('admin.system-settings.index', ['group' => $request->group])
            ->with('success', '系统设置更新成功，配置已同步！');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(SystemSetting $systemSetting)
    {
        $group = $systemSetting->group;
        $systemSetting->delete();

        return redirect()->route('admin.system-settings.index', ['group' => $group])
            ->with('success', '系统设置删除成功！');
    }

    /**
     * 批量更新设置
     */
    public function batchUpdate(Request $request)
    {
        $settings = $request->get('settings', []);
        
        DB::transaction(function () use ($settings) {
            foreach ($settings as $key => $value) {
                SystemSetting::set($key, $value);
            }
        });

        // 重新加载配置到Laravel配置系统
        SystemSetting::reloadConfigs();

        return redirect()->back()->with('success', '设置保存成功，配置已同步！');
    }

    /**
     * 清除缓存
     */
    public function clearCache()
    {
        SystemSetting::clearCache();
        
        return redirect()->back()->with('success', '缓存清除成功！');
    }

    /**
     * 导出设置
     */
    public function export()
    {
        $settings = SystemSetting::all();
        
        $filename = 'system_settings_' . date('Y-m-d_H-i-s') . '.json';
        
        return response()->json($settings->toArray())
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
    }

    /**
     * 导入设置
     */
    public function import(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|file|mimes:json'
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator);
        }

        $file = $request->file('file');
        $content = file_get_contents($file->getPathname());
        $settings = json_decode($content, true);

        if (!$settings) {
            return redirect()->back()
                ->with('error', '文件格式错误！');
        }

        DB::transaction(function () use ($settings) {
            foreach ($settings as $setting) {
                SystemSetting::updateOrCreate(
                    ['key' => $setting['key']],
                    $setting
                );
            }
        });

        return redirect()->back()->with('success', '设置导入成功！');
    }
}
